import { sourceUrl } from '@/config';
import { checkIsSold } from '@/dataTransfer/product';
import { JOIN_KEY } from '@/dataTransfer/skuManager';
import closeImg from '@/images/common/close1.png';
import addImage from '@/images/common/add.png';
import subImage from '@/images/common/sub.png';
import subDisImage from '@/images/common/sub-disabled.png';
import cartImg from '@/images/standBar/cart.png';
import homeImg from '@/images/standBar/home.png';
import meImg from '@/images/standBar/me.png';
import { debounce } from '@/utils/helper';
import utils from '@/utils/index';
import { Image, ScrollView, Text, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import classNames from 'classnames';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { AtFloatLayout } from 'taro-ui';
import Icon from '@/components/Icon';
import { customeColor } from '@/src/config';
import './index.scss';

const GoodsSpecSelect = (props) => {
  const [purchaseNum, setPurchaseNum] = useState(1);
  const [selOptions, setSelOptions] = useState([]);
  const [skuInfo, setSkuInfo] = useState({ price: 0 });
  const pDetail = useRef(null);
  const selectOp = useRef([])

  const handlePurchaseNum = (type) => {
    let num = purchaseNum;
    let isUnOk = showToastByType(type);
    if (isUnOk) return;
    if (type === 'add') num++;
    if (type === 'sub') num--;
    if (num < 1) num = 1;
    setPurchaseNum(num);
  };

  const showToastByType = (type = '') => {
    let title = '';
    if (Object.keys(skuInfo).length === 1) {
      title = '请选择商品属性';
    } else if (purchaseNum == 0) {
      title = '暂时缺货~';
    } else if (type === 'add' && purchaseNum >= skuInfo.inventoryQuantity) {
      title = '库存不多，不能再加啦~';
    } else if (type === 'sub' && purchaseNum <= 1) {
      title = '不能再少啦~';
    }
    if (title.length > 0) {
      Taro.showToast({
        title,
        icon: 'none',
        duration: 2500,
      });
    }
    return title.length ? true : false;
  };

  const goCartPage = () => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }
    utils.goCartPage(props.dispatch);
  };

  const handleOpSelect = (name, value,iop) => {
    let curSelOptions = [...selectOp.current];
    if(iop === 0){
      setSkuInfo({ price: 0 })
      curSelOptions = []
    }
    let i = 0;
    for (; i < curSelOptions.length; i++) {
      if (name === curSelOptions[i].name) {
        curSelOptions[i].value = value;
        break;
      }
    }
    if (i === curSelOptions.length) {
      curSelOptions.push({ name, value });
    }

    let sortSelOptions = [];
    for (let key in pDetail.current.options) {
      for (let j = 0; j < curSelOptions.length; j++) {
        if (key === curSelOptions[j].name) {
          sortSelOptions.push({ name: curSelOptions[j].name, value: curSelOptions[j].value });
          break;
        }
      }
    }
    pDetail.current.selObject = sortSelOptions
    selectOp.current = sortSelOptions
    setSelOptions(sortSelOptions);
  };

  const checkOptionIsStock = useCallback(
    ({ name, value }) => {
      if (!props.productDetail?.stockPath) {
        return false;
      }

      const stockPath = props.productDetail.stockPath;

      // 覆盖规格值
      let isSame = false;
      const options = selOptions.map((v) => {
        if (v.name === name) {
          isSame = true;
          return {
            ...v,
            value,
            fullPath: `${name}${JOIN_KEY}${value}`,
          };
        }

        return v;
      });

      // 添加规格值
      if (!isSame) {
        options.push({ name, value, fullPath: `${name}${JOIN_KEY}${value}` });
      }

      const isStock = checkIsSold(stockPath, options);

      return isStock;
    },
    [selOptions, props.productDetail],
  );

  const handleAddCart = debounce(() => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }
    let isUnOk = showToastByType();
    if (isUnOk) return;
    let delayTime = 0;
    if (skuInfo.activityLimit > 0 && purchaseNum > skuInfo.activityLimit) {
      delayTime = 1500;
      Taro.showToast({
        title:
          '该折扣商品限购' +
          skuInfo.activityLimit +
          '份,超过' +
          skuInfo.activityLimit +
          '份恢复原价',
        icon: 'none',
        mask: false,
        duration: 1500,
      });
    }
    props
      .dispatch({
        type: 'productList/addProduct',
        payload: {
          productReleaseId: pDetail.current.id,
          productVariantReleaseId: skuInfo.id,
          num: purchaseNum,
          merchantId: pDetail.current.merchantId,
          orgId: pDetail.current.storeId,
          orgName: pDetail.current.orgName,
          favouredId: skuInfo.activityId,
          favouredType: skuInfo.type,
          type: 1,
          selected: pDetail.current.selected,
        },
      })
      .then((res) => {
        setTimeout(() => {
          if (res.code === '1') {
            Taro.showToast({
              title: '成功加入购物车',
              icon: 'success',
              duration: 1500,
            });
            props.setVisible(false);

            // 加入购物车成功回调
            if (props.add2cartSuccess) {
              props.add2cartSuccess({
                product: { ...pDetail.current },
                skuInfo: { ...skuInfo },
                num: purchaseNum,
              });
            }
            if (props.refreashNumAfterAddSuccess) {
              props.refreashNumAfterAddSuccess();
            }
          } else {
            Taro.showToast({
              title: res.message || '加入购物车失败,请重试',
              icon: 'none',
              duration: 1500,
            });
          }
        }, delayTime);
      });
  }, 2000);

  const handleBuyNow = debounce(() => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }
    let isUnOk = showToastByType();
    if (isUnOk) return;
    let delayTime = 0;
    if (skuInfo.activityLimit > 0 && purchaseNum > skuInfo.activityLimit) {
      delayTime = 1500;
      Taro.showToast({
        title:
          '该折扣商品限购' +
          skuInfo.activityLimit +
          '份,超过' +
          skuInfo.activityLimit +
          '份恢复原价',
        icon: 'none',
        mask: false,
        duration: 1500,
      });
    }
    if (props.selectedAddress?.id) {
      props.dispatch({
        type: 'productCar/setDefaultAddress',
        payload: props.selectedAddress,
      });
    }
    props.dispatch({
      type: 'productCar/setBuyNow',
      payload: {
        num: purchaseNum,
        productReleaseId: pDetail.current.id,
        merchantId: pDetail.current.merchantId,
        orgName: pDetail.current.orgName,
        orgId: pDetail.current.storeId,
        productVariantReleaseId: skuInfo.id,
        favouredId: skuInfo.activityId,
        favouredType: skuInfo.type,
      },
    });

    let url = '/orderSubPack/confirmOrder/index?buyNow=1&merchantId=' +
      pDetail.current.merchantId +
      '&orgId=' +
      pDetail.current.storeId +
      '&type=1';
    setTimeout(() => {
      props.setVisible(false);
      Taro.navigateTo({ url });
    }, delayTime);
  }, 2000);

  const getOptionPrice = () => {
    props
      .dispatch({
        type: 'productList/getOptionPrice',
        payload: {
          productReleaseId: pDetail.current.id,
          options: selOptions,
          activityId: props.curProduct.activityId,
        },
      })
      .then((data) => {
        if(data?.code == '0'){
          setSelOptions([])
        }
        let showOptions = selOptions.map((op) => op.value);
        data.showOptionsStr = showOptions.join('，');
        if (data.type == '3') {
          let leftTimeStamp =
            new Date(data.endTime.replace(/-/g, '/').replace(/T/, ' ')) - new Date();
          data.leftTimeSM = leftTimeStamp >= 0 ? leftTimeStamp : 0;
        }
        setSkuInfo(data);
        props.getSkuSel({ selOptions, skuData: data });
        if (data.inventoryQuantity == 0) {
          setPurchaseNum(0);
        } else {
          setPurchaseNum(1);
        }
      });
  };

  useEffect(() => {
    if (!Object.keys(props.productDetail).length) {
      return;
    }
    pDetail.current = { ...props.productDetail };
    if (props.curOptions.length) {
      setSelOptions(props.curOptions);
    } else if (props.productDetail.defaultSel?.length) {
      setSelOptions(props.productDetail.defaultSel);
    }
  }, [props.productDetail]);

  useEffect(()=>{
    if(pDetail.current && !selOptions.length){
      Object.keys(pDetail.current.options).map((select,idx)=>{
        handleOpSelect(select, pDetail.current.options[select]?.[0],idx);
      })
    }
  },[pDetail.current])
  useEffect(() => {
    if (pDetail.current && selOptions.length === Object.keys(pDetail.current.options).length) {
      getOptionPrice();
    }
  }, [selOptions]);

  let optionsDom = [];
  if (props.visible) {
    const options = pDetail.current.options;
    const {isShowSpecialOptions = false,specialOptions} = pDetail?.current
    if(isShowSpecialOptions && !selOptions.length){
      let arr = [{
        name: specialOptions?.variantNames[0],
        value: specialOptions?.options[0].optionKey
      }]
      pDetail.current.selObject = arr
      setSelOptions(arr);
    }
    Object.keys(options).forEach((key,iop)=>{
      let opDomList = options[key].map((op, index) => {
        let active = false;
        for (let i = 0; i < selOptions.length; i++) {
          if (key === selOptions[i].name) {
            if (op === selOptions[i].value) {
              active = true;
            }
            break;
          }
        }
        const unSelectable = checkOptionIsStock({ name: key, value: op });
        return (
          <View
            className={
              'spec-item ' + (unSelectable ? 'unSelectable ' : '') +
              (active ? 'customePageStyleBg20 customePageBorderStyle' : '') + 
              (isShowSpecialOptions && iop == Object.keys(options).length-1 && !specialOptions?.options.find(res=>pDetail.current.selObject.find(ret=>ret.value === res.optionKey))?.optionValue?.find(ret=>ret==op)?'visibili':'')
            }
            key={key + '_' + op + index}
            onClick={() => {
              if (unSelectable) {
                return;
              }
              handleOpSelect(key, op,iop);
            }}
          >
            <View
              className={classNames(
                'text',
                active && 'customePageStyle',
                unSelectable && 'unSelectable',
              )}
            >
              {op}
            </View>
          </View>
        );
      });
      optionsDom.push(
        <>
          <View className={classNames('label-spec')} key={key + '_option'}>
            {key}
          </View>
          <View className="spec-group-wrap">
            <View className="spec-group">{opDomList}</View>
          </View>
        </>,
      );
    })
  }

  return (
    <View className="goodsSpecSelect" catchMove>
      <AtFloatLayout
        isOpened={props.visible}
        onClose={() => {
          props.setVisible(false);
        }}
      >
        <View className="inner">
          <View className="goods-info">
            <View className="goods">
              <Image
                // mode="widthFix"
                className="goodsSmallImg"
                src={
                  skuInfo.imageUrl?.length > 0
                    ? skuInfo.imageUrl.indexOf('http') === 0
                      ? skuInfo.imageUrl
                      : sourceUrl + skuInfo.imageUrl
                    : pDetail.current?.mediaList?.[0].url
                    ? pDetail.current?.mediaList?.[0].url.indexOf('http') === 0
                      ? pDetail.current?.mediaList?.[0].url
                      : sourceUrl + pDetail.current?.mediaList?.[0].url
                    : ''
                }
              />
              <View className="detail">
                <View className="priceLine">
                  <View className="price customePageStyle">
                    <Text className="unit">¥</Text>
                    <Text className="zNum">
                      {skuInfo.price > 0 ? skuInfo.price : pDetail.current?.price}
                    </Text>
                    <Text
                      className={classNames(
                        'zMore',
                        (skuInfo.price > 0 || pDetail.current?.isOnlyOne) && 'hidden',
                      )}
                    >
                      起
                    </Text>
                    {skuInfo.type == 3 && (
                      <View className="activityInfo customePageBorderStyle50">
                        <Icon name="icon_labe" size={18} color={customeColor} />
                        <Text className="discount">{skuInfo.discount}折</Text>
                        <Text className="diliver customePageBackgroundStyle"></Text>
                        <Text className="activityLimit">
                          {skuInfo.activityLimit == 0
                            ? '不限购'
                            : '限' + skuInfo.activityLimit + '件'}
                        </Text>
                      </View>
                    )}
                  </View>
                </View>

                <View className="curOp mt4">
                  {skuInfo.showOptionsStr?.length
                    ? '已选：' + skuInfo.showOptionsStr
                    : '请选择商品规格'}
                </View>
                <View className="curOp mt8">
                  {skuInfo.inventoryQuantity != undefined
                    ? '库存' + skuInfo.inventoryQuantity + '件'
                    : ''}
                </View>
              </View>
            </View>
            <View
              className="closeArea flex-row-center-center"
              onClick={() => props.setVisible(false)}
            >
              <Image src={closeImg} className="close-icon" />
            </View>
          </View>

          <View className="line" />

          <ScrollView className="sku-account" scrollY>
            <View className="skuSettings">{optionsDom.length > 0 && optionsDom}</View>
            <View className="line" />
            <View className="account">
              <Text className="left-text">购买数量</Text>
              <View className="number-sel">
                <View
                  className="opBox flex-row-center-center"
                  onClick={() => handlePurchaseNum('sub')}
                >
                  <Image
                    mode="widthFix"
                    className="sub"
                    src={purchaseNum > 1 ? subImage : subDisImage}
                  />
                </View>
                <View className="num">
                  <View className="value">{purchaseNum}</View>
                </View>
                <View
                  className="opBox flex-row-center-center"
                  onClick={() => handlePurchaseNum('add')}
                >
                  <Image mode="widthFix" className="add" src={addImage} />
                </View>
              </View>
            </View>
          </ScrollView>

          <View className={'emptyBottom' + (Taro.$bottomHight ? ' mbh' : '')}></View>

          <View className="bottom flex-column">
            <View className="bottomCtx flex-row--center">
              <View
                className="tab flex-column--center"
                onClick={() => utils.goHomePage(props.dispatch)}
              >
                <Image className="icon" src={homeImg} />
                <View className="name">首页</View>
              </View>
              {/* <View
                className="tab flex-column--center mlr21"
                onClick={() => utils.goMePage(props.dispatch)}
              >
                <Image className="icon" src={meImg} />
                <View className="name">我的</View>
              </View> */}
              <View className="tab flex-column--center mlr21" onClick={goCartPage}>
                <Image className="icon" src={cartImg} />
                <View className="name">购物车</View>
                {props.productNumInCart && props.productNumInCart > 0 && (
                  <View
                    className={[
                      'gwcNum customePageBackgroundStyle',
                      props.productNumInCart > 9 && 'two',
                      props.productNumInCart > 99 && 'three',
                    ].join(' ')}
                  >
                    {props.productNumInCart > 99 ? '99+' : props.productNumInCart}
                  </View>
                )}
              </View>

              <View className="ops flex-row-center-center">
                {(props.needSkuBy === 'buy' || props.needSkuBy === 'cart') && (
                  <Text
                    className={
                      'btnAll flex-row-center-center customePageBackgroundStyle' +
                      (skuInfo.inventoryQuantity === 0 ? ' disable' : '')
                    }
                    onClick={() => (props.needSkuBy === 'cart' ? handleAddCart() : handleBuyNow())}
                  >
                    确定
                  </Text>
                )}
                {props.needSkuBy === 'sku' && (
                  <>
                    <Text
                      className={
                        'left btn flex-row-center-center customePageStyleBg20 customePageStyle' +
                        (skuInfo.inventoryQuantity === 0 ? ' disable' : '')
                      }
                      onClick={handleAddCart}
                    >
                      加入购物车
                    </Text>
                    <Text
                      className={
                        'right btn flex-row-center-center customePageBackgroundStyle' +
                        (skuInfo.inventoryQuantity === 0 ? ' disable' : '')
                      }
                      onClick={handleBuyNow}
                    >
                      立即抢购
                    </Text>
                  </>
                )}
              </View>
            </View>
            {Taro.$bottomHight && <View className="bottomHt"></View>}
          </View>
        </View>
      </AtFloatLayout>
    </View>
  );
};
export default GoodsSpecSelect;
